﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using Avalonia.Platform;
using DevManager.Models;

namespace DevManager.Services;

public static class LanguageService
{
    public static LanguageList? GetList()
    {
        using var stream = AssetLoader.Open(new Uri("avares://DevManager/Assets/LanguageList.json"));
        using var reader = new StreamReader(stream);
        var result = reader.ReadToEnd();
        return JsonSerializer.Deserialize<LanguageList>(result);
    }

    public static List<AppUseModel> GetUse()
    {
        using var stream = AssetLoader.Open(new Uri("avares://DevManager/Assets/AppInstallAddUse.json"));
        using var reader = new StreamReader(stream);
        var result = reader.ReadToEnd();
        var list = JsonSerializer.Deserialize<List<AppUse>>(result);
        return list == null ? new List<AppUseModel>() : list.Select(x => x.UseToModel()).ToList();
    }

    private static AppUseModel UseToModel(this AppUse use)
    {
        var os = "";
        if (OperatingSystem.IsWindows())
        {
            os = "Windows";
        }else if (OperatingSystem.IsMacOS())
        {
            os = RuntimeInformation.ProcessArchitecture is Architecture.X64 or Architecture.X86
                ? "Mac(arm)"
                : "Mac(x86)";
        }

        var url = use.InstallUrls.FirstOrDefault(x => x.Name == os)?.Url;
        return new AppUseModel(){Description = use.Description,Name = use.Name,UseWord = use.UseWord,InstallUrl = url!};
    }
    
    public static InstalledModel IsInstalled(string lang, string s)
    {
        var r = new InstalledModel() { Name = lang };
        var list = s.Split("=");
        if (list.Length < 2) return r;
        if (list[0] == "Path")
        {
            if (!Directory.Exists(list[1]))
            {
                r.Versions = new[] { "Not Fount" };
                return r;
            }

            var folder = new DirectoryInfo(list[1]);
            r.IsInstalled = true;
            r.Versions = folder.GetDirectories().Select(x => x.Name).ToArray();
            return r;
        }

        if (list[0] == "Order")
        {
            var order = list[1].Split(" ");
            var runner = new CommandRunner(order[0]);
            var result = runner.Run(order[^1]);
            r.IsInstalled = true;
            r.Versions = result.Split("\n").Where(x => !string.IsNullOrEmpty(x)).Select(x => x.Replace("\r", ""))
                .ToArray();
            return r;
        }

        return r;
    }
}